package command;

import parser.ChessContentHandlerConstants;
import parser.ParserConstants;

public class ChessClockCommand implements Command {
	
	private Command secondaryCommand;
	private game.ChessGame currentGame;
	private chess.Player currentPlayer;
	private long elapsedTime;

	
	public ChessClockCommand(game.ChessGame curGame, long elapsedTime, chess.Player currentPlayer){
		this.currentGame=curGame;
		this.currentPlayer = currentPlayer;
		//System.out.println("CurrentPlayer : " + currentPlayer.getColour() + ", Time : " + elapsedTime);
		//elapsedTime = curGame.getClock().getElapsedTime();
		this.elapsedTime = elapsedTime;
		//System.out.println("Command made, Time: "+elapsedTime);
		this.secondaryCommand=new NoSecondaryCommand();
	}

	@Override
	public void addSecondaryCommand(Command secondaryCommand) {
		if (this.secondaryCommand instanceof NoSecondaryCommand){
			this.secondaryCommand = secondaryCommand;
		}
		else{
			this.secondaryCommand.addSecondaryCommand(secondaryCommand);
		}
		
	}

	@Override
	public void execute() {
		currentGame.getClock().updateTime(currentPlayer, elapsedTime);
		currentGame.getClock().switchPlayers(currentGame.getOpponent(currentPlayer));
		
	}

	@Override
	public String exportCode() {
		// TODO Caleb, fill this out.
		return "";
	}

	@Override
	public boolean hadMovedPreviously() {
		// Not necessary for this command
		return false;
	}

	@Override
	public void undo() {
		secondaryCommand.undo();
		//System.out.println("Undone");
		currentGame.getClock().undo(currentPlayer);
		currentGame.getClock().switchPlayers(currentPlayer);
		
	}

	@Override
	public String xmlCode() {
		String code = "<" + ParserConstants.ELEMENT_CHESS_CLOCK + ">\n";
		
		code += "\t" + xmlTimeTag().replaceAll("\n", "\n\t");
		code += "\n";
		code += "</" + ParserConstants.ELEMENT_CHESS_CLOCK + ">";
		code += secondaryCommand.xmlCode();
		return code;
	}
	private String xmlTimeTag(){
		String s = "<" + ChessContentHandlerConstants.ELEMENT_CURRENT_TIME + " ";
		s += ChessContentHandlerConstants.ATTRIBUTE_VALUE + "='" + elapsedTime + "'>";
		s += "</" + ChessContentHandlerConstants.ELEMENT_CURRENT_TIME + ">";
		return s;
	}
	@Override
	public Command getSecondaryCommand() {
		return this.secondaryCommand;
	}

}
